package executor.size;

/**
 * Support class for thread pool size
 *
 * @author Nadeem Mohammad
 */
public final class ThreadPoolUtil {

    private ThreadPoolUtil() {

    }

    /**
     * Each tasks blocks 90% of the time, and works only 10% of its
     * lifetime. That is, I/O intensive pool
     *
     * @return io intesive Thread pool size
     */
    public static int ioIntesivePoolSize() {
        double blockingCoefficient = 0.9;
        return poolSize(blockingCoefficient);
    }


    /**
     * Ncpu=CPU的数量
     * Ucpu=目标CPU使用率
     * W/C=等待时间与计算时间的比率
     *
     * 范围：0<=Ucpu<=1
     * 为保持处理器达到期望的使用率，最优的线程池的大小等于
     * Nthreads=Ncpu*Ucpu*（1+W/C）
     *
     * @return
     */

    public static int ioIntesivePoolSize2(double W_C) {
        int Ncpu = Runtime.getRuntime().availableProcessors();
        double Ucpu = 0.5;
        return (int)(Ncpu*Ucpu*(1+W_C));
    }



    //CPU密集
    //CPU密集型的话，一般配置CPU处理器个数+/-1个线程，所谓CPU密集型就是指系统大部分时间是在做程序正常的计算任务，
    //例如数字运算、赋值、分配内存、内存拷贝、循环、查找、排序等，这些处理都需要CPU来完成。
    public static int calcIntesivePoolSize() {
        return Runtime.getRuntime().availableProcessors() + 1;
    }


    /**
     * Number of threads = Number of Available Cores / (1 - Blocking
     * Coefficient) where the blocking coefficient is between 0 and 1.
     * <p>
     * A computation-intensive task has a blocking coefficient of 0, whereas an
     * IO-intensive task has a value close to 1,
     * so we don't have to worry about the value reaching 1.
     *
     * @param blockingCoefficient the coefficient
     * @return Thread pool size
     */
    public static int poolSize(double blockingCoefficient) {
        int numberOfCores = Runtime.getRuntime().availableProcessors();
        int poolSize = (int) (numberOfCores / (1 - blockingCoefficient));
        return poolSize;
    }
}